package com.wondertek.mist;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Arrays;
import java.util.List;

import org.apache.cordova.CordovaChromeClient;
import org.apache.cordova.CordovaWebViewClient;
import org.apache.cordova.DroidGap;
import org.json.JSONException;
import org.json.JSONObject;

import com.baidu.android.pushservice.PushConstants;
import com.baidu.android.pushservice.PushManager;
import com.umeng.socialize.PlatformConfig;
import com.umeng.socialize.UMShareAPI;
import com.wondertek.mist.database.DataHelper;
import com.wondertek.mist.plugins.BaiduPushPlugin;
import com.wondertek.mist.po.NotiPo;
import com.wondertek.mist.utils.AntiHijackingUtils;
import com.wondertek.mist.utils.DeviceUtils;
import com.wondertek.mist.utils.RUtil;
import com.wondertek.mist.utils.StringUtils;

import android.Manifest;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.WebSettings;
import android.webkit.WebSettings.RenderPriority;
import android.webkit.WebStorage.QuotaUpdater;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.Toast;


public class MistActivity extends DroidGap {

	final static String TAG="MistActivity";
	private Button goIndexBtn;
	private Button sendBtn;
	private Button closeBtn;

	
	private Handler handler = new Handler();
	
	private void showWebViewDialog(String url,String name, String flag){
		final Dialog dialog = new Dialog(this, RUtil.style(this, "dialog"));
		dialog.setCanceledOnTouchOutside(true);
		
		View dialogView = LayoutInflater.from(this).inflate(RUtil.layout(this, "dialog_webview"), null);
		goIndexBtn = (Button) dialogView.findViewById(RUtil.id(this,"goIndexBtn"));
		sendBtn = (Button) dialogView.findViewById(RUtil.id(this,"sendBtn"));
		closeBtn = (Button) dialogView.findViewById(RUtil.id(this,"closeBtn"));
		WebView webView = (WebView) dialogView.findViewById(RUtil.id(this,"dialog_wv"));
		
		////
		webView.getSettings().setRenderPriority(RenderPriority.HIGH);  
		
		webView.getSettings().setJavaScriptEnabled(true);
		
		////
		webView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
		webView.getSettings().setAppCacheEnabled(true);  
		webView.getSettings().setAllowFileAccess(true);
		
		String cacheDirPath = getFilesDir().getAbsolutePath()+"cfub";  
		webView.getSettings().setDatabasePath(cacheDirPath);  
	        //设置  Application Caches 缓存目录  
		webView.getSettings().setAppCachePath(cacheDirPath);  
		
		// 开启 DOM storage API 功能  
		webView.getSettings().setDomStorageEnabled(true);
		 //开启 database storage API 功能  
		webView.getSettings().setDatabaseEnabled(true);		
		
		
		webView.getSettings().setBuiltInZoomControls(true);
		webView.getSettings().setSupportZoom(true);
		webView.getSettings().setSupportMultipleWindows(true);
		webView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
		
		


		
		
		webView.setWebViewClient(new WebViewClient(){

			ProgressDialog progressDialog;
			@Override
			public void onPageFinished(WebView view, String url) {
				if(progressDialog!=null)
				    progressDialog.dismiss();
				super.onPageFinished(view, url);
			}

			@Override
			public void onPageStarted(WebView view, String url, Bitmap favicon) {
				progressDialog = com.eternity.util.Utils.progress(MistActivity.this, "页面正在加载", "请稍等……");
				super.onPageStarted(view, url, favicon);
			}
			
		});
		dialog.setContentView(dialogView);	
		
		if(flag != null && flag.equals("HOME")) {
			goIndexBtn.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					//ADT
					dialog.dismiss();
					MistActivity.this.appView.loadUrl("javascript:goToIndex()");
				}
			});
			sendBtn.setOnClickListener(new View.OnClickListener() {
				@Override
				public void onClick(View v) {
					//ADT
					dialog.dismiss();
					MistActivity.this.appView.loadUrl("javascript:sendPolicy()");
				}
			});
			closeBtn.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					dialog.dismiss();
				}
			});
		} else {
			goIndexBtn.setVisibility(View.GONE);
			sendBtn.setVisibility(View.GONE);
			closeBtn.setVisibility(View.GONE);
		}
	
//		if (StringUtils.isBlank(name)) {
//			button.setVisibility(View.GONE);
//		}else {
//			button.setVisibility(View.VISIBLE);
//			button.setText("返回");
//		}
		webView.loadUrl(url);
		dialog.show();
	}
	
	
	
	
	
	public void onCreate(Bundle savedInstanceState) {

		super.onCreate(savedInstanceState);
		super.init();
		//防止截屏
		//this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);
		
		String wxAppId=Utils.getMetaValue(this, "WX_APPID");
		String wxAppSecret=Utils.getMetaValue(this, "WX_APPSECRET");
		Log.i("wx", "wxAppId="+wxAppId+",wxAppSecret="+wxAppSecret);
		if(!StringUtils.isBlank(wxAppId) && !"#WX_APPID#".equalsIgnoreCase(wxAppId)){
			PlatformConfig.setWeixin(wxAppId, wxAppSecret);
		}
		
		
		
		this.appView.getSettings().setRenderPriority(RenderPriority.HIGH);
		this.appView.getSettings().setAppCacheMaxSize(50 * 1024 * 1024);
		this.appView.getSettings().setAppCachePath(this.getApplicationContext().getDir("cache", Context.MODE_PRIVATE).getPath());
		this.appView.getSettings().setAllowFileAccess(true);
		this.appView.getSettings().setAppCacheEnabled(true);
		this.appView.getSettings().setCacheMode(WebSettings.LOAD_DEFAULT);
	
		this.appView.setWebViewClient(new CordovaWebViewClient(this,
				this.appView) {

			@Override
			public boolean shouldOverrideUrlLoading(WebView view, String url) {
				view.loadUrl(url);
				view.requestFocus();
				return true;
			}
			
			@Override
			public void onReceivedSslError(WebView arg0, SslErrorHandler handler, SslError arg2) {
				handler.proceed();
			}

		});

		this.appView.setWebChromeClient(new CordovaChromeClient(this,
				this.appView) {
			@Override
			public void onReachedMaxAppCacheSize(long requiredStorage,
					long quota, QuotaUpdater quotaUpdater) {
				quotaUpdater.updateQuota(requiredStorage * 2);
			}
		});
		
		
		///this.appView.addJavascriptInterface(new JsKit(), "androidJs");
		
		
		//该Activity的最外层Layout
		final View activityRootView = this.appView.getRootView();
		//给该layout设置监听，监听其布局发生变化事件
		activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener(){
	
		    @Override
		    public void onGlobalLayout(){
		 
		       //比较Activity根布局与当前布局的大小
		    	int heightDiff = activityRootView.getRootView().getHeight()-  MistActivity.this.appView.getHeight();
		        if(heightDiff >100 || heightDiff==0){  //联想pad登录界面heightDiff=0
		            //大小超过100时，一般为显示虚拟键盘事件
		        	
		        }else{
		            //大小小于100时，为不显示虚拟键盘或虚拟键盘隐藏
		        	MistActivity.this.loadUrl("javascript:if(window.hideKeyboard){hideKeyboard();};");
		        }
		     }
		});
		
//        this.appView.clearCache(true);
		//兼容老版，未来将删除
		this.appView.addJavascriptInterface(new Object(){
			public void openPdf(final String pdffileUrl) {
				MistActivity.this.appView.pluginManager.exec("PdfViewer", "showPdf", null, "[\""+pdffileUrl+"\"]");
			}
			public void openHtml(final String url,final String name, final String flag) {
                
				handler.post(new Runnable(){

					@Override
					public void run() {
						showWebViewDialog(url,name, flag);
					}
					
				});
			}
			public String getMac() {
				return DeviceUtils.getDeviceMac(MistActivity.this);
			}
			public String getPushInfo() {
				JSONObject jsonObject = new JSONObject();
				String user_id = Utils.getString(MistActivity.this, "push.user_id");
				String channel_id = Utils.getString(MistActivity.this, "push.channel_id");
				try {
					jsonObject.put("userid", user_id);
					jsonObject.put("channelid", channel_id);
				} catch (JSONException e) {
					e.printStackTrace();
				}

				return jsonObject.toString();
			}

			public void setPushTag(String tag) {
				List<String> tags = Arrays.asList(tag.split(","));
				PushManager.setTags(MistActivity.this, tags);
			}
			
			public void setFinished() {
				BaiduPushPlugin.webviewReady=true;
			}
			
			public void returnToMAM(){
				Log.i("MistActivity","returnToMAM");
				MistActivity.this.appView.pluginManager.exec("MAM", "returnToAppstore", null, "[]");
			}
			
			public void startVideo(String url){
			   Intent it = new Intent(Intent.ACTION_VIEW);
			   it.setDataAndType(Uri.parse(url), "video/*");
			   startActivity(it);
			}
			
			public String getMamInfo(){
				return Utils.getString(MistActivity.this, "param");
			}
			
		}, "mist");
		
	
		String apiKey=Utils.getMetaValue(this, "push.api_key");
		if(!StringUtils.isBlank(apiKey)){
			String userId = Utils.getString(this, "push.user_id");
			String channelId = Utils.getString(this, "push.channel_id");
			//if (userId.equals("") || channelId.equals("")) {
				PushManager.startWork(this, PushConstants.LOGIN_TYPE_API_KEY,apiKey);
			//} 
		}
		String startURL=Utils.getMetaValue(this, "mist.url");
		if(!TrustHTTPS.trust(startURL)){
			Log.e("MistActivity", "服务器证书验证失败");
			Toast.makeText(this,"服务器证书验证失败", Toast.LENGTH_SHORT).show();
			int pid=android.os.Process.myPid();
			android.os.Process.killProcess(pid);
			return;
		}
		
		super.loadUrl(startURL);
		
		//prevent text selection on long tap
        this.appView.setOnLongClickListener(new View.OnLongClickListener() {
			
			@Override
			public boolean onLongClick(View v) {
				return true;
			}
		});
		
	}
	
	@Override
	public boolean dispatchKeyEvent(KeyEvent event) {
		 int keycode = event.getKeyCode();
	        int keyunicode = event.getUnicodeChar(event.getMetaState() );
	        char character = (char) keyunicode;
		Log.i("key Pressed", "character="+character);
		return super.dispatchKeyEvent(event);
	}
	
	@Override
	public void onBackPressed() {
		if(this.appView.canGoBack()){
			this.appView.goBack();
		}
		return;
	}
	
	protected void onNewIntent(Intent intent) {
		setIntent(intent);
		String action = intent.getAction();
		if (Utils.ACTION_NOTI.equals(action)) {
			if (!BaiduPushPlugin.webviewReady) {
				NotiPo notiPo = new NotiPo();
				notiPo.setTitle(intent.getStringExtra(PushConstants.EXTRA_NOTIFICATION_TITLE));
				notiPo.setContent(intent.getStringExtra(PushConstants.EXTRA_NOTIFICATION_CONTENT));
				notiPo.setExtra(intent.getStringExtra(PushConstants.EXTRA_EXTRA));

				DataHelper dataHelper = new DataHelper(this);
				dataHelper.saveNoti(notiPo);
				dataHelper.close();
			} else {
				
				DataHelper dataHelper = new DataHelper(this);
				List<NotiPo> notiPos = dataHelper.getAllNotis();
				dataHelper.delNoti();
				dataHelper.close();
				if (notiPos.size() == 0) {
					NotiPo notiPo = new NotiPo();
					notiPo.setTitle(intent.getStringExtra(PushConstants.EXTRA_NOTIFICATION_TITLE));
					notiPo.setContent(intent.getStringExtra(PushConstants.EXTRA_NOTIFICATION_CONTENT));
					notiPo.setExtra(intent.getStringExtra(PushConstants.EXTRA_EXTRA));
					notiPos.add(notiPo);
				}

				for (NotiPo notiPo : notiPos) {
					JSONObject jsonObject = new JSONObject();
					try {
						jsonObject.put("title", notiPo.getTitle());
						jsonObject.put("content", notiPo.getContent());
						if (notiPo.getExtra() != null) {
							jsonObject.put("extra", URLEncoder.encode(notiPo.getExtra(), "UTF-8"));
						} else {
							jsonObject.put("extra", notiPo.getExtra());
						}

					} catch (JSONException e) {
						e.printStackTrace();
					} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
					}
					this.appView.loadUrl("javascript: didReceiveRemoteNotification('"+ jsonObject.toString() + "')");
				}

			}
		}else if(Utils.ACTION_MAM.equals(action)){}
		
		

	}
	
	
	@Override
	public void onReceivedError(int arg0, String arg1, String arg2) {
         return;	
	}
	
	@Override
	protected void onStop() {
		boolean safe=AntiHijackingUtils.checkActivity(this);
        if(!safe) {
            //弹出警示信息
            Toast.makeText(getApplicationContext(), "您的界面被覆盖，请确认应用是否安全", Toast.LENGTH_SHORT).show();
           
        }
        super.onStop();
    }
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		
		String wxAppId=Utils.getMetaValue(this, "WX_APPID");
		if(!StringUtils.isBlank(wxAppId) && !"#WX_APPID#".equalsIgnoreCase(wxAppId)){
			UMShareAPI.get( this ).onActivityResult( requestCode, resultCode, data);
		}
	}
	
	
	/////////////////
/*	public class JsKit
	{
		*//*********** 支付宝支付功能 ***********//*
		@JavascriptInterface
		public void canvasPicture()
		{
	          Toast.makeText(getApplicationContext(), "您正在测试移动调用", Toast.LENGTH_SHORT).show();
			
		}
	}*/


}